package com.hkyp.ss.coursewebadmin.utils;

import com.hkyp.ss.course.apis.utils.JWTTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 获取用户的信息
 */
@Slf4j
public class UserSessionUtils {

    //获取用户Id,可能返回null
    public static Long getUserIdCanBeNull() {
        //long userId = (long)(Math.random() * 100)+1;   //[1,100)
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String userId = JWTTokenUtil.getUserId(token);
        log.info("从token中解析出的userId:{}",userId);
        Long userIdlong = null;
        if(!StringUtils.isEmpty(userId)){
            userIdlong =   Long.valueOf(userId);
        }
        return userIdlong;
    }

    // todo 如果获取为空，可以抛出NoLoginException,异常处理器捕获后返回相应code
    //获取用户Id
    public static Long getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            log.error("token获取为空，认为是身份未认证/未登录");
            throw new UnauthenticatedException("身份未认证，请先登录");
        }
        String userId = JWTTokenUtil.getUserId(token);
        log.info("从token中解析出的userId:{}",userId);
        Long userIdlong = null;

        if(!StringUtils.isEmpty(userId)){
            userIdlong =   Long.valueOf(userId);
        }else {
            log.error("获取userId为空，认为是身份未认证/未登录");
            throw new UnauthenticatedException("身份未认证，请先登录");
        }
        return userIdlong;
    }



    //获取用户Token
    public static String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token;
    }

}
